package cn.edu.java.io.outputstream;

import java.io.IOException;
import java.io.PipedOutputStream;
import java.io.PipedInputStream;

public class PipedOutputStreamDemo {
    public static void main(String[] args) {
        try {
            // 创建PipedOutputStream和PipedInputStream
            PipedOutputStream pipedOutputStream = new PipedOutputStream();
            PipedInputStream pipedInputStream = new PipedInputStream();

            // 将PipedOutputStream和PipedInputStream连接起来
            pipedOutputStream.connect(pipedInputStream);

            // 创建一个线程用于向PipedOutputStream写入数据
            Thread writerThread = new Thread(() -> {
                try {
                    String message = "Hello, PipedOutputStream!";
                    pipedOutputStream.write(message.getBytes());
                    System.out.println("发生信息：" + message);
                    pipedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            // 创建一个线程用于从PipedInputStream读取数据
            Thread readerThread = new Thread(() -> {
                try {
                    int data;
                    while ((data = pipedInputStream.read()) != -1) {
                        System.out.print((char) data);
                    }
                    System.out.println("\n接收完毕！");
                    pipedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            // 启动线程
            writerThread.start();
            readerThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

